package com.shujia.wyh.udtfdemos;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

/*
    编写自定义函数UDTF的步骤：
    1、自定义类需要继承GenericUDTF
 */
public class MyUDTFDemo1 extends GenericUDTF {

    /**
     *  输入：
     *      "key1:value1,key2:value2,key3:value3"
     *  输出：
     *        key1 value1
     *        key2 value2
     *        key3 value3
     */
    //重写initialize方法的目的是构造最终产生的一行数据的列的个数以及列的类型
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建集合,将来存储列构造器（列名）
        ArrayList<String> filedNames = new ArrayList<String>();
        //列的类型
        ArrayList<ObjectInspector> filedObj = new ArrayList<ObjectInspector>();

        filedNames.add("col1");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("col2");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(filedNames, filedObj);
    }

    //重写process的目的是最终调用时进行处理的逻辑
    @Override
    public void process(Object[] args) throws HiveException {
        //"key1:value1,key2:value2,key3:value3"
        String line = args[0].toString();
        String[] strings = line.split(",");
        for (String keyValue : strings) {
            String[] strings1 = keyValue.split(":");
            forward(strings1);
        }

    }

    //结束函数调用时会调用该方法
    @Override
    public void close() throws HiveException {

    }
}
